<template>
  <div class="page-wapper">
    <!-- 用户管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">角色名：</div>
            <el-input
              v-model="filterData.roleName"
              size="small"
              placeholder="请输入"
            ></el-input>
          </div>

          <div v-if="$isSupperAdmin()" class="filter_item">
            <div class="label">所属机构：</div>
            <OrgSelect v-model:modelValue="orgInfo" @change="handleSearch" />
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <!-- 标签筛选列 -->
        <el-popover placement="bottom-start" trigger="click" width="600px">
          <div style="display: flex; flex-wrap: wrap">
            <div style="width: 200px">
              <el-checkbox
                v-model="columnsAll.visible"
                @change="tagCheckedChange(columnsAll)"
                >全选
              </el-checkbox>
            </div>
            <template v-for="(item, i) in columns">
              <div v-if="item.title" :key="i" style="width: 200px">
                <el-checkbox
                  v-model="item.visible"
                  :disabled="disabledCancleColumns.includes(item.title)"
                  @change="tagCheckedChange(item)"
                  >{{ item.title }}
                </el-checkbox>
              </div>
            </template>
          </div>

          <template #reference>
            <el-button type="primary" size="mini">筛选列</el-button>
          </template>
        </el-popover>
        <div>
          <el-button
            v-if="$hasPermission($permission.ROLE_SAVE_OR_UPDATE)"
            size="mini"
            type="primary"
            @click="createTableData"
          >
            新建
          </el-button>
          <el-button
            v-if="$hasPermission($permission.ROLE_DELETE)"
            size="mini"
            type="danger"
            @click="batchdelete"
          >
            删除
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :checkbox-config="{
            checkField: 'checked',
            trigger: 'row',
            checkMethod: tableCheckMethod,
          }"
          :row-style="rowStyle"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>
          <TableColum :colums="tableColum">
            <template #asUse="{ props }">
              <div style="text-align: center" @click.stop="">
                <el-switch
                  v-model="props.row.asUse"
                  :loading="props.row.asUseLoading"
                  @change="changeAsUse(props.row)"
                  :disabled="disabledRoleNameList.includes(props.row.roleName)"
                />
              </div>
            </template>
          </TableColum>
          <vxe-column #default="{ row }" width="180" title="操作" fixed="right">
            <div>
              <el-button
                v-if="
                  !disabledRoleNameList.includes(row.roleName) &&
                  $hasPermission($permission.ROLE_SAVE_OR_UPDATE)
                "
                size="mini"
                type="text"
                style="color: #409eff"
                @click.stop="editTableDataMethod(row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="$hasPermission($permission.PERMISSION_PAGE)"
                size="mini"
                type="text"
                style="color: #67c23a"
                @click.stop="editPermissionMethod(row)"
              >
                编辑权限
              </el-button>
              <!-- <el-button
                v-if="row.asUse && $hasPermission($permission.ROLE_TOGGLE_USE)"
                size="mini"
                type="text"
                style="color: #f56c6c"
                @click.stop="handleStopUse(row, true)"
              >
                停用
              </el-button>
              <el-button
                v-else-if="
                  !row.asUse && $hasPermission($permission.ROLE_TOGGLE_USE)
                "
                size="mini"
                type="text"
                style="color: #67c23a"
                @click.stop="handleStopUse(row, false)"
              >
                启用
              </el-button> -->
              <el-button
                v-if="
                  !disabledRoleNameList.includes(row.roleName) &&
                  $hasPermission($permission.ROLE_DELETE)
                "
                size="mini"
                type="text"
                style="color: #f56c6c"
                @click.stop="deleteTableDataMethod(row)"
              >
                删除角色
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 编辑弹框 -->
    <RoleFormDialog ref="roleFormDialogRef" @refresh="getTableData" />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  nextTick,
  getCurrentInstance,
  computed,
  toRefs,
  onMounted,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import RoleFormDialog from "./components/RoleFormDialog.vue";
import TableColum from "../../components/TabelTemplate/TableColum.vue";
import OrgSelect from "../../components/OrgSelect.vue";

const initFilterData = () => {
  return {
    roleName: null,
    asUse: null,
    orgId: null,
  };
};

export default {
  name: "RoleManage",
  components: { RoleFormDialog, TableColum, OrgSelect },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);

    // 机构选择组件绑定的数据
    const orgInfo = ref({
      orgId: null,
      orgName: null,
    });

    // 初始化需要禁用的角色名
    const disabledRoleNameList = ref([]);

    const roleFormDialogRef = ref(null);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);

    const tableState = reactive({
      columnsAll: {
        visible: true,
        title: "全选",
      },
      // 标签筛选列
      columns: [],
      // 列表标签筛选需要禁用筛选的选项
      disabledCancleColumns: ["序号", "操作"],
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        roleName: {
          title: "角色名",
          props: { sortable: false },
        },
        orgName: {
          title: "所属机构",
          props: { sortable: false },
        },
      },
    });

    // 判断有没有修改使用的权限
    if (proxy.$hasPermission(proxy.$permission.ROLE_TOGGLE_USE)) {
      tableState.tableColum.asUse = {
        title: "是否使用",
        props: { sortable: false, width: 160, fixed: "right" },
        slotContent: "asUse",
      };
    }

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      resetOrgData();
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      // 处理机构搜索参数
      condition.orgId = orgInfo.value.orgId;
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      $api.role
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              asUseLoading: false,
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 新建
    const createTableData = () => {
      if (!condition.orgId) {
        return ElMessage.warning("请先选择机构");
      }
      nextTick(() => {
        roleFormDialogRef.value.open(condition.orgId);
      });
    };

    // 编辑内容
    const editTableDataMethod = (row) => {
      nextTick(() => {
        roleFormDialogRef.value.open(row.orgId, row);
      });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 阻止删除【普通用户】角色
      if (row && row.roleName === "普通用户") {
        return ElMessage.warning("普通用户角色为默认角色，不可删除");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.roleName.length > 10
            ? row.roleName.slice(0, 10) + "..."
            : row.roleName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 批量删除
    const batchdelete = () => {
      if (!tableState.tableData.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableState.tableData.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 阻止删除【普通用户】角色
      if (selectedList.some((item) => item.roleName === "普通用户")) {
        return ElMessage.warning("普通用户角色为默认角色，不可删除");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableState.tableLoading = true;
      $api.role
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 设置启用或停用
    const changeAsUse = (row) => {
      row.asUseLoading = true;
      $api.role
        .toggleUse({
          id: row.id,
          asUse: row.asUse,
        })
        .then((res) => {
          ElMessage.success("操作成功");
        })
        .catch((err) => {
          console.error("toggleUse error: ", err);
        })
        .finally(() => {
          row.asUseLoading = false;
          getTableData();
        });
    };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        tableState.columns.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            tableState.disabledCancleColumns.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      tableState.columnsAll.visible = tableState.columns.every(
        (item) => item.visible
      );
      // 刷新布局
      tableState.xTable.refreshColumn();
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
          // backgroundColor: 'lightblue',
          // color: '#ffffff'
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 编辑权限
    const editPermissionMethod = (row) => {
      router.push({
        path: "/PermissionManage",
        query: {
          id: row.id,
        },
      });
    };

    // 列表勾选行的禁用
    const tableCheckMethod = ({ row }) => {
      return !disabledRoleNameList.value.includes(row.roleName);
    };

    // 获取初始化的角色名列表
    const listInitRoleName = () => {
      $api.role
        .listInitRoleName({})
        .then((res) => {
          disabledRoleNameList.value = res.data || [];
        })
        .catch((err) => {
          console.error("listInitRoleName error: ", err);
        });
    };

    // 是否停用
    const handleStopUse = (row, isStop) => {
      ElMessageBox.confirm(
        `确定要${isStop ? "停用" : "启用"}【${
          row.roleName.length > 10
            ? row.roleName.slice(0, 10) + "..."
            : row.roleName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {})
        .catch(() => {});
    };

    // 重置机构绑定数据-初始值为当前登录人绑定的机构信息
    const resetOrgData = () => {
      // 此数据必须在 dom 挂载之后初始化，否则 v-model 绑定数据无法流向子组件
      orgInfo.value.orgId = userInfo.value.orgId;
      orgInfo.value.orgName = userInfo.value.orgName;
    };

    // 初始化
    const initPageData = () => {
      resetOrgData();
      // 必须放在 resetOrgData 之后
      handleSearch();
    };

    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        tableState.columns = tableState.xTable.getColumns();
      });
    }, 100);

    listInitRoleName();
    onMounted(() => {
      initPageData();
    });

    return {
      rowStyle,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      createTableData,
      editTableDataMethod,
      deleteTableDataMethod,
      tagCheckedChange,
      getTableData,
      roleFormDialogRef,
      pagenationData,
      tableCheckMethod,
      handleSizeChange,
      handleCurrentChange,
      batchdelete,
      changeAsUse,
      orgInfo,
      editPermissionMethod,
      disabledRoleNameList,
      handleStopUse,
      ...toRefs(tableState),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
